<?php
/**
 * Created by PhpStorm.
 * User: lf
 * Date: 16/4/12
 * Time: 22:15
 */
namespace feehi\components;


use yii;
use backend\models\AdminRoles;
use yii\base\Component;
use backend\models\AdminRoleUser;
use backend\models\AdminRolePermission;


class Rbac extends Component
{
    private $_superAdministrators;

    private $_noNeedAuthentication = ['site/login', 'site/main'];

    private $_role_id;

    private $_roleName;

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        foreach ($this->_noNeedAuthentication as &$v){
            if( substr_count($v, '/')<2 ) $v = yii::$app->id.'/'.$v;
        }
    }

    public function checkPermission($uid='')
    {//var_dump($this->_noNeedAuthentication);die;
        if($uid == 1) return true;
        if( in_array(yii::$app->user->identity->username, $this->_superAdministrators) ) return true;
        $route = strtolower( Yii::$app->controller->module->id.'/'.Yii::$app->controller->id.'/'.Yii::$app->controller->action->id );
        if( in_array($route, $this->_noNeedAuthentication) ) return true;
        $this->getRoleId($uid);
        if($this->_role_id == 1) return true;
        $permissions = AdminRolePermission::getPermissionsByRoleId($this->_role_id);
        $method = strtolower( yii::$app->request->getMethod() );
        foreach($permissions as $permission){
            if( substr_count($permission['url'], '/')<2 ) $permission['url'] = yii::$app->id.'/'.$permission['url'];
            if( strtolower($permission['url']) == $route ){
                if($permission['method'] == 'all' || $permission['method'] == $method){
                    return true;
                }
            }
        }
        return false;
    }

    public function setSuperAdministrators(array $params)
    {
        $this->_superAdministrators = $params;
    }

    public function getSuperAdministrators()
    {
        return $this->_superAdministrators;
    }

    public function setNoNeedAuthentication(array $params)
    {
        $this->_noNeedAuthentication = $params;
    }

    public function getNoNeedAuthentication()
    {
        return $this->_noNeedAuthentication;
    }

    public function getRoleId($uid='')
    {
        if($uid == '') yii::$app->user->identity->id;
        $this->_role_id = AdminRoleUser::getRoleId($uid);
        return $this->_role_id;
    }

    public function getRoleName()
    {
        $this->_roleName = AdminRoles::getRoleNameByUid();
        return $this->_roleName;
    }

}